package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.Music;
import com.qf.service.Impl.MusicServiceImpl;
import com.qf.service.MusicService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author yangl
 * @version 1.0
 * @date 2023/4/20 15:45
 *
 * 查询所有歌曲
 */
@WebServlet("/musicFindByPageServlet.action")
public class MusicFindByPageServlet extends HttpServlet {

    private MusicService musicService = new MusicServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取分页数据
        //获取当前页码
        String page = req.getParameter("page");
        //判断
        if(page == null){
            page = "1";//默认访问第一页
        }
        //获取每页显示条数
        String limit = req.getParameter("limit");
        //判断
        if(limit == null){
            limit = "2";//默认每页显示两条数据
        }

        //查询每页显示的数据
        List<Music> musicList = musicService.findByPage(page,limit);

        //查询总记录数
        Long count = musicService.queryTotalCount();

        //返回前端UI框架的指定格式
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        map.put("count",count);//设置是总数量
        map.put("data",musicList);//设置是分页数据

        String jsonMap = JSON.toJSONString(map);

        resp.getWriter().write(jsonMap);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
